<template>
  <div class="profile-shot">
    <!-- 顶部导航 -->
    <header class="top-bar">
      <i class="fa fa-arrow-left" @click="goBack" />
      <span>{{ topTitle }}</span>
      <i class="fa fa-ellipsis-h" />
    </header>

    <!-- 主页内容 -->
    <transition name="slide">
      <div v-if="page === 'main'" class="main-page">
        <!-- 用户卡片 -->
        <section class="card user-info-card">
          <div class="avatar-box" @click="page = 'avatar'">
            <img v-if="user && user.photo" :src="user.photo" alt="头像" />
            <i v-else class="fa fa-user-circle default-avatar" />
            <div class="camera-badge">
              <i class="fa fa-camera" />
            </div>
          </div>
          <div class="base-info">
            <h3>{{ fullName }}</h3>
            <p>用户ID: {{ user.id }}</p>
            <!-- 管理员徽章 -->
            <div v-if="isAdmin" class="admin-badge">
              <i class="fa fa-star"></i>
              <span>管理员</span>
            </div>
          </div>
        </section>

        <!-- 功能列表 -->
        <ul class="func-list">
          <li v-for="(it, idx) in funcList" :key="idx" @click="it.click">
            <i :class="it.icon" :style="{ color: it.color }" />
            <span>{{ it.name }}</span>
            <i class="fa fa-angle-right arrow" />
          </li>

          <!-- 管理员专属功能 -->
          <div v-if="isAdmin" class="admin-section">
            <div class="section-divider">
              <span>管理员功能</span>
            </div>
            <li @click="goToAdmin">
              <i class="fa fa-cog" style="color: #FF6B6B;" />
              <span>管理员后台</span>
              <i class="fa fa-angle-right arrow" />
            </li>
          </div>
        </ul>
      </div>

      <!-- 子页面：修改姓名 -->
      <div v-else-if="page === 'name'" class="sub-page">
        <div class="field">
          <label>名</label>
          <input v-model="form.firstName" placeholder="请输入名" />
        </div>
        <div class="field">
          <label>姓</label>
          <input v-model="form.lastName" placeholder="请输入姓" />
        </div>
        <div class="btn-wrap">
          <button class="primary" @click="saveName">保存</button>
        </div>
      </div>

      <!-- 子页面：修改密码 -->
      <div v-else-if="page === 'pwd'" class="sub-page">
        <div class="field">
          <label>旧密码</label>
          <input v-model="pwd.old" type="password" placeholder="请输入旧密码" />
        </div>
        <div class="field">
          <label>新密码</label>
          <input v-model="pwd.new" type="password" placeholder="请输入新密码" />
        </div>
        <div class="field">
          <label>确认新密码</label>
          <input v-model="pwd.confirm" type="password" placeholder="再次输入" />
        </div>
        <div class="btn-wrap">
          <button class="primary" @click="savePwd">保存</button>
        </div>
      </div>

      <!-- 子页面：联系客服 -->
      <div v-else-if="page === 'contact'" class="sub-page contact">
        <div class="line">
          <i class="fa fa-phone" />
          <span>400-123-4567</span>
          <button class="copy" @click="copyContact">复制</button>
        </div>
        <div class="line">
          <i class="fa fa-clock" />
          <span>09:00-18:00</span>
        </div>
        <div class="line">
          <i class="fa fa-wechat" />
          <span>eleme_service</span>
          <button class="copy" @click="copyContact">复制</button>
        </div>
        <div class="line">
          <i class="fa fa-envelope" />
          <span>service@eleme.com</span>
          <button class="copy" @click="copyContact">复制</button>
        </div>
        <p class="tips">工作时间客服在线，其余时间请留言</p>
      </div>

      <!-- 头像子页 -->
      <div v-else-if="page === 'avatar'" class="sub-page avatar">
        <input type="file" accept="image/*" @change="onSelectFile" />
        <img v-if="preview" :src="preview" class="preview" />
        <button class="primary" @click="saveAvatar">上传并保存</button>
      </div>
    </transition>

    <!-- 底部导航 -->
    <!-- 底部菜单部分 -->
    <footer class="bottom-nav">
      <div class="nav-item" :class="{ active: $route.path === '/index' }" @click="$router.push('/index')">
        <i class="fa fa-home"></i>
        <span>首页</span>
      </div>
      <div class="nav-item">
        <i class="fa fa-compass"></i>
        <span>商家</span>
      </div>
      <div class="nav-item" :class="{ active: $route.path === '/orderList' }" @click="$router.push('/orderList')">
        <i class="far fa-file-alt"></i>
        <span>订单</span>
      </div>
      <div class="nav-item active">
        <i class="fa fa-user"></i>
        <span>我的</span>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

/* 状态 */
const loading = ref(false)
const err = ref('')
const user = ref({})
const UA = ref({})
const page = ref('main')           // main | name | pwd | contact | avatar
const preview = ref('')
const fileRaw = ref(null)
const form = ref({ firstName: '', lastName: '' })
const pwd = ref({ old: '', new: '', confirm: '' })
const token = ref(localStorage.getItem('token'))
const id = ref('')
const { proxy } = getCurrentInstance()
const router = useRouter()

/* 计算属性 */
const fullName = computed(() =>
  [user.value.firstName, user.value.lastName].filter(Boolean).join(' ') || '未设置姓名'
)

const isAdmin = computed(() => {
  return UA.value.authorities?.[0] === 'ADMIN'
})

/* 顶部标题 */
const topTitle = computed(() => {
  switch (page.value) {
    case 'name': return '修改姓名'
    case 'pwd': return '修改密码'
    case 'contact': return '联系客服'
    case 'avatar': return '修改头像'
    default: return '个人主页'
  }
})

/* 功能列表 */
const funcList = [
  { name: '我的钱包', icon: 'fa fa-wallet', color: '#4CAF50', click: () => router.push('/wallet') },
  { name: '修改头像', icon: 'fa fa-image', color: '#00bcd4', click: () => page.value = 'avatar' },
  { name: '修改姓名', icon: 'fa fa-user', color: '#0097FF', click: () => page.value = 'name' },
  { name: '修改密码', icon: 'fa fa-lock', color: '#FF9800', click: () => page.value = 'pwd' },
  { name: '我的评论', icon: 'far fa-comment-alt', color: '#9C27B0', click: () => router.push('/myComments') },
  { name: '联系客服', icon: 'fa fa-headphones', color: '#F44336', click: () => page.value = 'contact' },
  { name: '退出登录', icon: 'fa fa-sign-out', color: '#E91E63', click: logout }
  
]

/* 底部导航 */
const tabs = [
  { name: '首页', icon: 'fa fa-home', active: false, click: () => router.push('/index') },
  { name: '商家', icon: 'fa fa-compass', active: false, click: () => router.push('/mine') },
  { name: '订单', icon: 'fa fa-file-text-o', active: false, click: () => router.push('/orderList') },
  { name: '我的', icon: 'fa fa-user-o', active: true, click: () => { } }
]

/* 返回逻辑 */
function goBack() {
  if (page.value === 'main') router.back()
  else page.value = 'main'
}

/* 管理员功能 */
function goToAdmin() {
  ElMessage.success('进入管理员后台')
  router.push('/Administrator')
}

/* 接口方法 */
async function load() {
  loading.value = true
  err.value = ''
  try {
    const response = await proxy.$axios.get(`/user`, {
      headers: { 'Authorization': `Bearer ${token.value}` }
    })
    UA.value = response.data.data
    user.value.id = UA.value.id

    const userResponse = await proxy.$axios.get(`/persons/${user.value.id}`, {
      headers: { 'Authorization': `Bearer ${token.value}` }
    })
    user.value = userResponse.data.data
    id.value = user.value.id || ''
    form.value = { firstName: user.value.firstName || '', lastName: user.value.lastName || '' }

    console.log('用户权限信息:', UA.value.authorities?.[0])
    console.log('是否为管理员:', isAdmin.value)
  } catch (e) {
    err.value = '加载失败，请重试'
    console.error('加载用户信息失败:', e)
  }
  loading.value = false
}

function onSelectFile(e) {
  const file = e.target.files[0]
  if (!file || !file.type.startsWith('image/')) {
    ElMessage.error('请选择图片')
    return
  }

  const reader = new FileReader()
  reader.onload = () => {
    preview.value = reader.result
    fileRaw.value = reader.result
  }
  reader.readAsDataURL(file)
}

async function saveAvatar() {
  if (!fileRaw.value) return ElMessage.warning('请选择图片')

  try {
    const base64 = fileRaw.value
    await proxy.$axios.put('/user', {
      "id": user.value.id,
      "firstName": user.value.firstName,
      "lastName": user.value.lastName,
      "email": user.value.email,
      "phone": user.value.phone,
      "gender": user.value.gender,
      "photo": base64
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })

    user.value.photo = base64
    ElMessage.success('头像已更新')
    page.value = 'main'
  } catch (e) {
    console.error(e)
    ElMessage.error('上传头像失败')
  }
}

async function saveName() {
  if (!form.value.firstName && !form.value.lastName) {
    return ElMessage.warning('至少填写姓或名中的一项')
  }

  try {
    await proxy.$axios.put('/user', {
      "id": user.value.id,
      "firstName": form.value.firstName,
      "lastName": form.value.lastName,
      "email": user.value.email,
      "phone": user.value.phone,
      "gender": user.value.gender,
      "photo": user.value.photo
    }, {
      headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    })

    user.value.firstName = form.value.firstName
    user.value.lastName = form.value.lastName

    ElMessage.success('姓名已保存')
    page.value = 'main'
  } catch (e) {
    console.error(e)
    ElMessage.error('保存失败，请稍后再试')
  }
}

async function savePwd() {
  if (pwd.value.new !== pwd.value.confirm) return ElMessage.warning('两次密码不一致');
  try {
    // 1. 用旧密码验证身份
    await proxy.$axios.post('auth', {
      username: user.value.username,
      password: pwd.value.old  // 使用旧密码
    }, {
      headers: { 'Content-Type': 'application/json' }
    });

    // 2. 旧密码验证通过后，再修改密码
    await proxy.$axios.post('/password', {
      username: user.value.username,
      password: pwd.value.new
    }, {
      headers: {
        Authorization: `Bearer ${token.value}`,
        'Content-Type': 'application/json'
      }
    });

    ElMessage.success('密码已修改，请重新登录');
    localStorage.removeItem('token');
    router.push('/login');
  } catch (error) {
    // 3. 处理认证失败（401表示旧密码错误）
    if (error.response?.status === 401) {
      ElMessage.warning('原密码错误');
    } else {
      ElMessage.error('修改密码失败，请稍后再试');
    }
  }
}

function copyContact() {
  const txt = `客服电话：400-123-4567\n工作时间：09:00-18:00\n微信：eleme_service\n邮箱：service@eleme.com`
  navigator.clipboard.writeText(txt).then(() => ElMessage.success('已复制到剪贴板'))
}

function logout() {
  localStorage.removeItem('token')
  router.push('/indxe')
}

onMounted(load)
</script>



<style scoped>
/* ---------- 整体样式优化 ---------- */
.profile-shot {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f4f8 100%);
  min-height: 100vh;
  padding-bottom: 18vw;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  color: #333;
}

/* ---------- 顶部导航栏美化 ---------- */
.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 12vw;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 4vw;
  z-index: 100;
  transition: all 0.3s ease;
}

.top-bar i {
  font-size: 5vw;
  color: #4a5568;
  cursor: pointer;
  transition: color 0.2s;
}

.top-bar i:hover {
  color: #0097FF;
}

.top-bar span {
  font-weight: 600;
  font-size: 4.5vw;
  flex: 1;
  text-align: center;
  color: #2d3748;
}

/* ---------- 用户卡片美化 ---------- */
.user-info-card {
  margin: 4vw;
  background: linear-gradient(135deg, #ffffff 0%, #f7fafc 100%);
  border-radius: 16px;
  padding: 6vw;
  display: flex;
  align-items: center;
  box-shadow: 0 10px 25px rgba(0, 151, 255, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
  position: relative;
}

.user-info-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 30px rgba(0, 151, 255, 0.15);
}

.avatar-box {
  position: relative;
  margin-right: 5vw;
  cursor: pointer;
  transition: transform 0.3s;
}

.avatar-box:hover {
  transform: scale(1.05);
}

.avatar-box img {
  width: 22vw;
  height: 22vw;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.avatar-box .default-avatar {
  font-size: 20vw;
  color: #cbd5e0;
}

.avatar-box .camera-badge {
  position: absolute;
  bottom: 0;
  right: 0;
  background: linear-gradient(135deg, #0097FF 0%, #0062cc 100%);
  color: #fff;
  width: 8vw;
  height: 8vw;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 3.5vw;
  box-shadow: 0 2px 8px rgba(0, 151, 255, 0.4);
  transition: all 0.3s;
}

.avatar-box .camera-badge:hover {
  transform: scale(1.1);
}

.base-info h3 {
  font-size: 5.5vw;
  margin: 0 0 1vw;
  color: #2d3748;
  font-weight: 700;
}

.base-info p {
  font-size: 3.5vw;
  color: #718096;
  margin: 0;
}

/* 管理员徽章 */
.admin-badge {
  display: inline-flex;
  align-items: center;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E8E 100%);
  color: white;
  padding: 1vw 2.5vw;
  border-radius: 20px;
  font-size: 3vw;
  margin-top: 2vw;
  box-shadow: 0 3px 10px rgba(255, 107, 107, 0.3);
  animation: pulse 2s infinite;
}

.admin-badge i {
  margin-right: 1.5vw;
  font-size: 3.5vw;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }

  100% {
    transform: scale(1);
  }
}

/* 管理员功能区 */
.admin-section {
  margin-top: 3vw;
}

.section-divider {
  display: flex;
  align-items: center;
  margin: 4vw 0 2vw;
  color: #718096;
  font-size: 3.8vw;
  font-weight: 600;
}

.section-divider::before,
.section-divider::after {
  content: "";
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #cbd5e0, transparent);
}

.section-divider span {
  padding: 0 3vw;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8f4f8 100%);
}

/* ---------- 功能列表美化 ---------- */
.func-list {
  margin: 4vw;
  background: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.func-list li {
  display: flex;
  align-items: center;
  padding: 4.5vw 5vw;
  border-bottom: 1px solid #edf2f7;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.func-list li:last-child {
  border: none;
}

.func-list li:hover {
  background-color: #f7fafc;
  transform: translateX(5px);
}

.func-list li i:first-child {
  font-size: 5.5vw;
  width: 8vw;
  text-align: center;
  margin-right: 3vw;
  transition: transform 0.3s;
}

.func-list li:hover i:first-child {
  transform: scale(1.2);
}

.func-list li span {
  flex: 1;
  font-size: 4.2vw;
  color: #2d3748;
  font-weight: 500;
}

.func-list li .arrow {
  font-size: 4.5vw;
  color: #cbd5e0;
  transition: transform 0.3s;
}

.func-list li:hover .arrow {
  color: #0097FF;
  transform: translateX(3px);
}

/* 管理员功能项特殊样式 */
.admin-section li {
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-left: 4px solid #4ECDC4;
}

.admin-section li:hover {
  background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
  border-left-color: #FF6B6B;
  transform: translateX(8px);
}

/* ---------- 表单元素美化 ---------- */
.sub-page {
  padding: 12vw 4vw 4vw;
  animation: fadeIn 0.4s ease;
}

.field {
  margin-bottom: 5vw;
  position: relative;
}

.field label {
  display: block;
  font-size: 3.8vw;
  color: #4a5568;
  margin-bottom: 2vw;
  font-weight: 500;
}

.field input {
  width: 100%;
  padding: 3.5vw;
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  font-size: 4vw;
  transition: all 0.3s;
  background: #f7fafc;
}

.field input:focus {
  outline: none;
  border-color: #0097FF;
  box-shadow: 0 0 0 3px rgba(0, 151, 255, 0.2);
  background: #fff;
}

.btn-wrap {
  margin-top: 8vw;
}

button.primary {
  width: 100%;
  height: 12vw;
  background: linear-gradient(135deg, #0097FF 0%, #0062cc 100%);
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 4.5vw;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 10px rgba(0, 151, 255, 0.3);
}

button.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 15px rgba(0, 151, 255, 0.4);
}

button.primary:active {
  transform: translateY(0);
}

/* ---------- 联系客服页面美化 ---------- */
.contact .line {
  display: flex;
  align-items: center;
  padding: 4.5vw 0;
  border-bottom: 1px solid #e2e8f0;
  transition: background-color 0.3s;
}

.contact .line:hover {
  background-color: #f7fafc;
  border-radius: 8px;
  padding-left: 3vw;
}

.contact .line i {
  font-size: 5vw;
  width: 8vw;
  text-align: center;
  color: #0097FF;
}

.contact .line span {
  flex: 1;
  font-size: 4vw;
  color: #2d3748;
}

.contact .line .copy {
  padding: 2.5vw 5vw;
  background: linear-gradient(135deg, #edf2f7 0%, #e2e8f0 100%);
  border: none;
  border-radius: 8px;
  font-size: 3.5vw;
  color: #4a5568;
  cursor: pointer;
  transition: all 0.3s;
}

.contact .line .copy:hover {
  background: linear-gradient(135deg, #0097FF 0%, #0062cc 100%);
  color: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 151, 255, 0.3);
}

.contact .tips {
  font-size: 3.5vw;
  color: #718096;
  margin-top: 6vw;
  text-align: center;
  font-style: italic;
}

/* ---------- 头像上传页面美化 ---------- */
.avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  animation: fadeIn 0.4s ease;
}

.avatar input[type="file"] {
  margin-bottom: 6vw;
  padding: 4vw;
  border: 2px dashed #cbd5e0;
  border-radius: 12px;
  width: 100%;
  text-align: center;
  transition: all 0.3s;
  background: #f7fafc;
  cursor: pointer;
}

.avatar input[type="file"]:hover {
  border-color: #0097FF;
  background: #edf2f7;
}

.preview {
  width: 40vw;
  height: 40vw;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  margin: 4vw 0;
  transition: all 0.5s;
}

.preview:hover {
  transform: scale(1.05);
  box-shadow: 0 12px 25px rgba(0, 0, 0, 0.2);
}

/* ---------- 底部导航栏美化 ---------- */
/* 底部导航 */
.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 16vw;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 3vw;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 2vw;
  border-radius: 10px;
}

.nav-item.active {
  color: #0097FF;
  transform: translateY(-3px);
}

.nav-item i {
  font-size: 5.5vw;
  margin-bottom: 1vw;
  transition: all 0.3s ease;
}

.nav-item.active i {
  transform: scale(1.2);
}

.nav-item span {
  font-size: 3vw;
  font-weight: 500;
}

.main-page {
  padding-top: 12vw;
}

/* ---------- 动画效果 ---------- */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.slide-enter-active,
.slide-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-enter-from {
  opacity: 0;
  transform: translateX(100%);
}

.slide-leave-to {
  opacity: 0;
  transform: translateX(-100%);
}

/* ---------- 响应式设计 ---------- */
@media (min-width: 768px) {
  .profile-shot {
    max-width: 500px;
    margin: 0 auto;
  }

  .top-bar {
    height: 60px;
    padding: 0 20px;
  }

  .top-bar i {
    font-size: 24px;
  }

  .top-bar span {
    font-size: 20px;
  }

  /* 其他桌面端适配样式... */
}
</style>